<?php
namespace app\index\controller;
use think\Request;
use think\Db;
/**
* 
*/
class Earthdata extends \think\Controller
{
	
	public function getData(){
		$request = Request::instance();
                if($request->isPost()){
                	$data = $request->except(['name']);
                	$city = trim($data['city']) == '' ? '阳原' : trim($data['city']);
                	$handel = trim($data['handel']);
                }
                $exportData = '';
                switch ($handel) {
                	case 'as':
                		$exportData = $this->asData($city);
                		break;

                	case 'econ':
                		$exportData = $this->econData($city);
                		break;

                	case 'envir':
                		$exportData = $this->envirData($city);
                		break;

                	case 'gover':
                		$exportData = $this->goverData($city);
                		break;

                	case 'peo':
                		$exportData = $this->peoData($city);
                		break;

                	case 'td':
                		$exportData = $this->tdData($city);
                		break;

                	case 'topo':
                		$exportData = $this->asData($city);
                		break;
                	
                	default:
                		$exportData = $this->packData(null);
                		break;
                }
                $exportData = json_encode($exportData);
                return $exportData;
	}

	protected function asData($city){

	}

	protected function econData($city){
		$result = Db::table('eqtinformationnew')->field('eqtname, GDP,FST_INDUSTRY,SND_INDUSTRY,TRD_INDUSTRY,Economics')->where("NEWEST = 1 and eqtname ='".$city."'")->select();
                //var_dump($result);
                return $this->packData($result);
	}

	protected function envirData($city){
		$result = Db::table('eqtinformationnew')->field('eqtname, altitudeL, altitudeAverage,
                        altitudeH, altitudeCenter, topographic')->where("NEWEST = 1 and eqtname ='".$city."'")->select();
                return $this->packData($result);
	}

	protected function goverData($city){
		
	}

	protected function peoData($city){
		$result = Db::table('eqtinformationnew')->field('eqtname, POP_ALL, POP_COUNTRYSIDE,
                        POP_TOWN, urbanAverIncome, villageAverIncom, villageNum, townNum,Population')->where("NEWEST = 1 and eqtname ='".$city."'")->select();
                return $this->packData($result);
	}

	protected function tdData($city){
		$province = Db::table('eqtinformationnew')
                ->field('province, x_longitude, x_latitude, MAGNITUDE, EQTTIME')
                ->where("eqtname = '".$city."' and NEWEST = 1")
                ->buildSql();
                $provinces = Db::field('ps.province, ps.neighbor, p.x_longitude, p.x_latitude, p.MAGNITUDE, p.EQTTIME')
                ->table('province ps,'.$province.' p')
                ->where('ps.province = p.province')
                ->select();
                //var_dump($provinces);
                //此处有一个隐患数据库里的分隔符采用的是中文的逗号
                $result = explode('，', $provinces[0]["neighbor"]);
                array_push($result, $provinces[0]["province"]);
                $lat = $provinces[0]["x_latitude"];
                $lon = $provinces[0]["x_longitude"];
                $magn = $provinces[0]["MAGNITUDE"];
                $eqtime = $provinces[0]["EQTTIME"];

                $nearCityData = $this->findNearCityData($result, $lat, $lon,$city);
                $hisEqData = $this->findHisEq($magn, $lat, $lon, $eqtime);

                $data = [
                        'nearCityData'  =>      $nearCityData,
                        'hisEqData'     =>      $hisEqData
                ];
                return $this->packData($data);
	}
        //地形地貌同环境信息
	/*protected function topoData($city){
		
	}*/

	protected function packData($data) {
		$stutas = $data== '' || $data == null ? 404 : 200;
		return $exportData = [
			'stutas'	=>	$stutas,
			'data'	=>	$data
		];
	}
        protected function findNearCityData($pro,$lat,$lon,$name){
                $map = [
                        'name' => ['<>', $name],
                        'province' => ['in',$pro]
                ];
                $result = Db::table('base')
                ->field("name,longitude,latitude,area,GDP,POP_ALL,ROUND(6378.138*2*asin(sqrt(pow(sin( (".$lat."*pi()/180-latitude*pi()/180)/2),2)+cos(".$lat."*pi()/180)*cos(latitude*pi()/180)* pow(sin( (".$lon."*pi()/180-longitude*pi()/180)/2),2)))*1000)/1000 as distence")
                ->where($map)
                ->order('distence')
                ->limit(4)
                ->select();
                return $result;
        }

        protected function findHisEq($magn, $lat, $lon, $eqtime){
                $range = 0;
                $unit = 1000; //单位(千米)
                $minTime = 999999; //最近时间
                $minDistence = 999999; //最近距离
                $maxMagn = 0; //最大震级
                $exportLength = 0;//记录长度
                $_onekey = '';
                $_twokey = '';
                $_thrkey = '';//记录key值
                $exportData = '';
                $oneSection = 5.0;
                $twoSection = 6.0;

                

                $exclude = array();
                if (0 < $magn && $magn <= 5.0) {
                        $range = 20*$unit;
                }else if ($magn > 5.0 && $magn <= 5.9) {
                        $range = 40*$unit;
                }else if ($magn > 5.9 && $magn <= 6.9) {
                        $range = 100*$unit;
                }else if ($magn > 6.9 && $magn <= 7.9) {
                        $range = 200*$unit;
                }else if ($magn > 7.9) {
                        $range = 400*$unit;
                }
                $map = [
                        "ROUND(6378.138*2*asin(sqrt(pow(sin( (".$lat."*pi()/180-latitude*pi()/180)/2),2)+cos(".$lat."*pi()/180)*cos(latitude*pi()/180)* pow(sin( (".$lon."*pi()/180-longitude*pi()/180)/2),2)))*1000)"  =>      ['<=', $range]
                ];
                $packData = Db::table('hisedisaster')
                ->field("OBJECTID,EarthquakeDate, Macro_epicenter, Magnitude, CrackDegree, Death, Area, DirectEconomicLoss, Latitude, Longitude")
                ->where($map)
                ->select();
                $minTime = 999999; //最近时间，只计算了年
                //$minDistence = 999999; //最近距离
                $maxMagn = 0 ; //最大震级
                //找出最大震级
                foreach ($packData as $key => $value) {
                       if($value["Magnitude"] > $maxMagn){
                        $maxMagn = $value["Magnitude"];
                        $_onekey = $key;
                       }
                }
                //找出时间最近，震级大于5级的最大震级，排除第一条，
                $maxMagn = 0;//重置
                foreach ($packData as $key => $value) {
                        $_time = $this->getYear($value['EarthquakeDate']);
                       if($value["Magnitude"] > $maxMagn && $key != $_onekey && $value["Magnitude"] > $oneSection && $_time < $minTime){
                        $maxMagn = $value["Magnitude"];
                        $minTime = $_time;
                        $_twokey = $key;
                       }
                }
                //找出时间最近，震级大于6级的最大震级，排除第一、二条，
                $maxMagn = 0;//重置
                $minTime = 999999;
                foreach ($packData as $key => $value) {
                        $_time = $this->getYear($value['EarthquakeDate']);
                       if($value["Magnitude"] > $maxMagn &&  $key != $_onekey && $key != $_twokey && $value["Magnitude"] > $twoSection && $_time < $minTime){
                        $maxMagn = $value["Magnitude"];
                        $minTime = $_time;
                        $_thrkey = $key;
                       }
                }
                $hisOne = $packData[$_onekey];
                $hisSec = $packData[$_twokey];
                $hisThr = $packData[$_thrkey];

                /*var_dump($hisOne);
                var_dump($hisTwo);
                var_dump($hisThr);*/
                $exportData['hisOne'] = $hisOne;
                $exportData['hisSec'] = $hisSec;
                $exportData['hisThr'] = $hisThr;
                return $exportData;
        }

        protected function getDistence($Data, $lat, $lon, $dunit = 1, $decimal = 2) {

                $EARTH_RADIUS = 6370.996; // 地球半径系数
                $PI = 3.1415926;

                $radLatS = $lat*$PI/180.0;
                $radLatE = $Data["Latitude"]*$PI/180.0;

                $radLonS = $lon*$PI/180.0;
                $radLonE = $Data["Longitude"]*$PI/180.0;

                $a = $radLatS - $radLatE;
                $b = $radLonS - $radLonE;

                $distence = 2*asin(sqrt(pow(sin($a/2),2) + cos($radLatE) * cos($radLatE) * pow(sin($b/2),2)));
                $distence = $distence*$EARTH_RADIUS*1000;

                if($dunit == 2){
                        $distence = $distence/1000; 
                }

                return round($distence, $decimal);
        }

        protected function getYear($time) {
                $strType = is_numeric($time);
                        
                if($strType) {
                        return $time;
                }else{
                        $str = '[-]';
                        $type = preg_match($str, $time);
                        if($type) {
                                return explode('-', $time)[0];
                        }
                }
                
        }
}
?>